package com.sphere.freereader.parser;

import android.util.Log;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import java.util.ArrayList;
import java.util.List;
import com.sphere.freereader.constant.Constants;
import com.sphere.freereader.entity.BookItem;

import com.sphere.freereader.R;
/**
 * Created by aquarius on 2016/8/8.
 */
public class HtmlParser {

    private static final String TAG = "HtmlParser";

    /**
     * 解析html得到书籍列表
     * @param htmlContent
     * @return
     */
    public static List<BookItem> getBookList(String category, String htmlContent) {
        List<BookItem> bookList = new ArrayList<BookItem>();
        try {
            Document doc = Jsoup.parse(htmlContent);
            // bookIndex 的ul标签第一次出现的地方
            Element content = doc.select("ul.bookIndex").first();
            Elements elements = content.select("li");
            for (int i = 0; i < elements.size(); i++) {
                Element item = elements.get(i);
                Element link = item.select("a").first();
                String bookUrl = link.attr("href");
                if(!bookUrl.contains("www.sbkk8.cn")) {
                    bookUrl = Constants.HOST_PATH + bookUrl;
                }
                String name = item.text();
                String imgUrl = item.select("img").attr("src");
                if (!imgUrl.contains("sbkk8")) {
                    imgUrl = Constants.HOST_PATH + imgUrl;
                }
                // 这里设置为30个就没有加载不出来的情况了 加载172个太多的原因？？？
                //if(bookList.size() > 30) break;
                bookList.add(new BookItem(category, name, bookUrl, imgUrl));
            }
        } catch (Exception e) {
            Log.e(TAG,"解析书本列表出现失败!! " + e.toString());
        }
        return bookList;
    }


    /**
     * 解析一个章节的内容
     * @param htmlStr
     * @return TODO 这里最好完整解析Chapter中所有的字段 并返回chapterInfo类型
     */
    public static String parseContentOfOneChapter(Document doc){
        Element element = doc.getElementById(Constants.ARTICLE_TAG);
        String realContent = element.text().replaceAll(" {1,}", "\r\n  ");
        return realContent;
    }

    public static String parseContentOfOneChapter(String htmlStr){
        Document doc = Jsoup.parse(htmlStr.replaceAll("<u>一</u>", ""));
        return parseContentOfOneChapter(doc);
    }

    // 文章内容中是否包含无用的下划线
    public static boolean isContainUnderlineTag(String htmlStr) {
        return htmlStr.contains("<u>一</u>");
    }
}
